package com.study.bigwork.user.controller;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.gson.Gson;
import com.study.bigwork.entity.User;
import com.study.bigwork.user.service.UserService;
import com.study.bigwork.util.GetInfo;

import io.rong.models.response.TokenResult;

@Controller
@RequestMapping("user")
public class UserController {
	@Resource
	private UserService userService;
	@RequestMapping(value="/money")
	public void changeClappingMoneyById(HttpServletRequest request,HttpServletResponse response) throws IOException {
			request.setCharacterEncoding("utf-8");
	        response.setContentType("application/json;charset=utf-8");
	        StringBuffer stringBuffer = new StringBuffer();
	        //line保存读取请求信息的当前一行，responseMessage为响应信息，返回信息
	        String line = null, responseMessage = null;
	        //输出流
	        PrintWriter out = response.getWriter();
	        //BufferedReader为缓冲读取流
	        BufferedReader bufferedReader = request.getReader();
	        while((line = bufferedReader.readLine()) != null){
	            stringBuffer.append(line);
	        }
	        System.out.println("controller:客户端传过来的信息为"+stringBuffer);
	        //将json数据转为String
	        Gson gson = new Gson();
	        User user =gson.fromJson(stringBuffer.toString(), User.class);
	        //进行修改客户拍拍币信息
	        boolean a = this.userService.updateClappingMoney(user);
	        if(a) {//修改成功
	        	responseMessage = "修改成功";
	        	System.out.println("修改成功");
	        }else {//修改失败
	        	responseMessage = "修改失败";
	        	System.out.println("修改失败");
	        }
	        //输出流将信息返回
	        out.print(responseMessage);
		}	
	
	@RequestMapping(value="/updateUserInfo",method = RequestMethod.POST)
	public void updateUserInfo(HttpServletRequest request,HttpServletResponse response) throws IOException {
		// 设置编码方式
				try {
					request.setCharacterEncoding("utf-8");
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				// 设置返回数据格式和编码
				response.setContentType("application/json;charset=utf-8");

				// 定义StringBuffer变量
				StringBuffer stringBuffer = new StringBuffer();
				// line保存读取请求信息的当前一行，responseMessage为响应信息，返回信息
				String line = null, responseMessage = null;

				// 输出流
				PrintWriter out = response.getWriter();

				// 读取信息时会发生IO异常
				try {
					// BufferedReader为缓冲读取流
					BufferedReader bufferedReader = request.getReader();
					while ((line = bufferedReader.readLine()) != null) {
						stringBuffer.append(line);
					}
					System.out.println(stringBuffer);

				} catch (IOException e) {
					e.printStackTrace();
				}

				// 将json数据转为String
				Gson gson = new Gson();
				User user = gson.fromJson(stringBuffer.toString(), User.class);
				boolean b = false;
				System.out.println(user.toString());
				// 调用CircleService类中addCircle方法访问数据库，并返回查询结果
				
				b = userService.updateUserInfo(user);
				responseMessage = b+"";

				System.out.println("返回的数据 " + responseMessage);
				// 输出流将信息返回
				out.print(responseMessage);
	}
	
	
	//获取用户的信息
	@RequestMapping(value="/getUserInfo/{id}",method = RequestMethod.GET)
	public void getUserInfo(@PathVariable("id") String id,HttpServletRequest request,HttpServletResponse response) throws IOException {
		// 设置编码方式
			request.setCharacterEncoding("utf-8");
			// 设置返回数据格式和编码
			response.setContentType("application/json;charset=utf-8");

			// 定义StringBuffer变量
			StringBuffer stringBuffer = new StringBuffer();
			// line保存读取请求信息的当前一行，responseMessage为响应信息，返回信息
			String line = null, responseMessage = null;

			// 输出流
			PrintWriter out = response.getWriter();
			try {
				out = response.getWriter();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			// 读取信息时会发生IO异常
			try {
				// BufferedReader为缓冲读取流
				BufferedReader bufferedReader = request.getReader();
				while ((line = bufferedReader.readLine()) != null) {
					stringBuffer.append(line);
				}
				System.out.println(stringBuffer);

			} catch (IOException e) {
				e.printStackTrace();
			}

			// 将json数据转为String
			Gson gson = new Gson();
			User user = new User();
			boolean b = false;
			user = userService.findUserById(Integer.parseInt(id));
			responseMessage = gson.toJson(user);
			System.out.println("对象转为json " + responseMessage);
			// 输出流将信息返回
			out.print(responseMessage);
	}
	
	//手机号+密码
	@RequestMapping(value="/login/{phoneNumber}",method = RequestMethod.POST)
	public void loginByNumberAndPassword(@PathVariable("phoneNumber") String phoneNumber,HttpServletRequest request,HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
      	StringBuffer stringBuffer = new StringBuffer();
        //line保存读取请求信息的当前一行，responseMessage为响应信息，返回信息
        String line = null, responseMessage = null;
        //用来保存对象
        User user = new User();
        //输出流
        PrintWriter out = response.getWriter();
        //BufferedReader为缓冲读取流
        BufferedReader bufferedReader = request.getReader();
        while((line = bufferedReader.readLine()) != null){
            stringBuffer.append(line);
        }
        System.out.println("controller:客户端传过来的信息为"+stringBuffer);
        //将json数据转为String
        Gson gson = new Gson();
        User user1 =gson.fromJson(stringBuffer.toString(), User.class);
        if(phoneNumber == null) {
        	 //调用service层，看信息是否匹配
            user = this.userService.findUserByPhoneNumberAndPassword(user1);
        }else {
        	//使用手机号+验证码
            boolean a = this.userService.isExist(user1);
            if(a) {//用户存在
            	System.out.println("用户存在!");
            	user = this.userService.findUserByPhoneNumber(user1);
            }else {//给用户注册
            	GetInfo getInfo = new GetInfo();
    			TokenResult tokenResult = getInfo.getToken("user");
    			String chat_id = tokenResult.getUserId();
    			String chat_token = tokenResult.getToken();
    			//给用户赋值
    			user1.setNickname(phoneNumber);
    			user1.setChat_id(chat_id);
    			user1.setChat_token(chat_token);
    			System.out.println("准备添加的用户对象为"+user1.toString());
    			//添加到数据库中
    			boolean b = this.userService.addUser(user1);
    			if(b) {
    				System.out.println("添加成功");
    				user = this.userService.findUserByPhoneNumber(user1);
    			}else {
    				System.out.println("添加失败");
    				user = user1;
    			}
            }
        }
      
        responseMessage = gson.toJson(user);
        System.out.println("对象转为json " + responseMessage);
        //输出流将信息返回
        out.print(responseMessage);
	}
	//获取chat信息
	@RequestMapping(value="/getChatInfo",method = RequestMethod.POST)
	public void getChatInfo(HttpServletRequest request,HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		//设置返回数据格式和编码
        response.setContentType("application/json;charset=utf-8");
        
        //定义StringBuffer变量
      	StringBuffer stringBuffer = new StringBuffer();
        //line保存读取请求信息的当前一行，responseMessage为响应信息，返回信息
        String line = null, responseMessage = null;
        
        //输出流
        PrintWriter out = response.getWriter();
        
        //读取信息时会发生IO异常
        try{
            //BufferedReader为缓冲读取流
            BufferedReader bufferedReader = request.getReader();
            while((line = bufferedReader.readLine()) != null){
                stringBuffer.append(line);
            }
            System.out.println(stringBuffer);
            
        }catch(IOException e){
            e.printStackTrace();
        }
        
        //将json数据转为String
        Gson gson = new Gson();
        User user = new User();
        User user1 =gson.fromJson(stringBuffer.toString(), User.class);
        System.out.println("得到的参数chat_id："+user1.getChat_id());
        boolean b = false;
        
        //调用UserService类中isExistUser方法访问数据库，并返回查询结果
        user = this.userService.getChatInfo(user1);
        responseMessage = gson.toJson(user);
        System.out.println("对象转为json " + responseMessage);
        //输出流将信息返回
        out.print(responseMessage);
	}
	@RequestMapping(value="/uploadUserImage/{imgName}",method = RequestMethod.POST)
	public void upLoadUserImage(@PathVariable("imgName") String imgName,HttpServletRequest request,HttpServletResponse response) throws IOException {
		// 设置编码方式
		request.setCharacterEncoding("utf-8");
		//设置返回数据格式和编码
		response.setContentType("application/json;charset=utf-8");
		
		// 接收客户端上传的文件
		System.out.println("修改的用户头像"+imgName);
		String address = request.getServletContext().getRealPath("/");
		 String path ="./userImage/"+ imgName+".jpg";
		InputStream in = request.getInputStream();
		FileOutputStream fos = new FileOutputStream(address + path);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = in.read(buffer)) != -1) {
			fos.write(buffer, 0, len);
		}
		fos.flush();
		fos.close();
		in.close();
		response.getWriter().append("true");		
	}
}
